package com.woyao;

import android.Manifest;
import android.app.Application;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.CardView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;
import com.woyao.core.model.ApplyResponse;
import com.woyao.core.model.BaseResponse;
import com.woyao.core.model.ChanceSummary;
import com.woyao.core.model.DemandSummary;
import com.woyao.core.model.GetChildHowResponse;
import com.woyao.core.model.GetMyDemandResponse;
import com.woyao.core.model.GetNextChancesResponse;
import com.woyao.core.model.How;
import com.woyao.core.model.KeyValueList;
import com.woyao.core.model.Manager;
import com.woyao.core.model.ProfileResponse;
import com.woyao.core.model.User;
import com.woyao.core.service.AccountService;
import com.woyao.core.service.ChanceService;
import com.woyao.core.service.HowService;
import com.woyao.core.util.Common;
import com.woyao.core.util.DateUtil;
import com.woyao.core.util.ServiceFactory;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import retrofit2.Call;

import static android.content.Context.LOCATION_SERVICE;
import static android.content.Context.MODE_PRIVATE;
import static com.woyao.WoyaoooApplication.userId;

public class ChancesFragment extends Fragment {
    private static final String FILE_PATH = Environment.getExternalStorageDirectory() + "/woyaoooupdate/";
    private static final String FILE_NAME = FILE_PATH + "woyaoooo" + DateUtil.format(new Date(), "yyMMddHHmmss") + ".apk";
    private String apk_path = "https://woyaohezuo.oss-cn-hangzhou.aliyuncs.com/woyaooo.apk";

    private ChancesFragment.OnChancesFragmentInteractionListener mListener;
    public View theview;
    Toolbar toolbar;

    private TextView matchDemand;

    List<String> mPermissionList = new ArrayList<>();

    ArrayList<String> howList = new ArrayList<>();



    private TextView statusTxt;
    private TextView orderTxt;


    LinearLayout applyBtn;
    LinearLayout goutongBtn;
    LinearLayout markBtn;
    LinearLayout shareBtn;

    ImageView markImageView;
    ImageView applyImageView;
    ImageView tempShareImageView;

    LinearLayout moreBtn;
    LinearLayout categoryBtn;
    LinearLayout publishBtn;
//    TextView serviceText;

    CardView main_chance;
    public UserViewModel uvm;
    LinearLayout chanceAll;
    FrameLayout emptyAll;
    Button matchBtn;
    TextView applyText;
    TextView summaryText;
    TextView sloganText;

    Button addDemandBtn;
    Button personBtn;
    Button modifyPreferBtn;

    Button messageBtn;


    Boolean loading = false;

    ProgressDialog progressDialog;

    private Integer COMPLETE_ACCOUNT_CODE = 10;
    private Integer COMPLETE_LOCATION_CODE = 30;
    private Integer COMPLETE_CATEGORY_CODE = 55;   //
    private Integer COMPLETE_VEFIFY_CODE = 60;   //

    private Integer ADD_DEMAND_CODE = 2000;
    private Integer MODIFY_DEMAND_CODE = 3000;
    private Integer MYREGISTER_CODE = 4000;
    private Integer COMPLETE_PREFER_CODE = 6000;

    private Integer MY_LOGIN_CODE = 4500;
    private Integer MY_ADDMEMBER_CODE = 5000;

    private static final int ASKCONTACTS_CODE = 2;
    private static final int PERMISSION_REQUEST_STORAGE = 1;
    private static final int ASKLOCATION_CODE = 3;
    private Integer INSTALL_CODE = 333;
    private Integer ADD_UPDATE_CODE  =7000;
    private Integer ADD_MEMBER_CODE  =8000;

    private String today;
    private ViewPager mViewPager;
    private ArrayList<ChanceSummary> chances = new ArrayList<ChanceSummary>();
    //    private List<View> mViews;  //存放视图的数组
//    private View view1,view2,view3;
    private ChanceSummaryAdapter mPagerAdapter;//适配器

    private Integer current = 0;


    public ChancesFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment ChancesFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ChancesFragment newInstance(String param1, String param2) {
        ChancesFragment fragment = new ChancesFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        uvm = ViewModelProviders.of(getActivity()).get(UserViewModel.class);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        theview = inflater.inflate(R.layout.fragment_chances, container, false);

        toolbar = (android.support.v7.widget.Toolbar) theview.findViewById(R.id.toolBar);
////        toolbar.setLogo(R.drawable.ic_launcher);
        toolbar.setTitle("我要合作网");
        toolbar.inflateMenu(R.menu.chance);

        Menu menu = toolbar.getMenu();
        if (menu != null) {
            try {
                //如果不为空,就反射拿到menu的setOptionalIconsVisible方法
                Method method = menu.getClass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE);
                //暴力访问该方法
                method.setAccessible(true);
                //调用该方法显示icon
                method.invoke(menu, true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {

                if (item.getItemId() == R.id.nav_search) {
                    Intent intent = new Intent();
                    intent.setClass(getContext(), SearchActivity.class);
                    startActivity(intent);
                }


                if (item.getItemId() == R.id.nav_publish_demand) {

                    if (!WoyaoooApplication.hasLogin) {
                        Intent intent = new Intent();
                        intent.setClass(getContext(), RegisterActivity.class);
                        startActivityForResult(intent, MYREGISTER_CODE);
                        return false;
                    }


                    if ( uvm.getUser().getDisplayname().equals("") ){
                        Dialog alertDialog = new AlertDialog.Builder(getContext()).
                                setTitle("信息").
                                setMessage("请填写个人资料").
                                setIcon(R.drawable.ic_launcher).
                                setPositiveButton("确定", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        CompleteAccount();
                                    }
                                }).
                                create();
                        alertDialog.show();
                        return false;
                    }

                    if ( uvm.getUser().getDemand_id() == 0 ){

                        Dialog alertDialog = new AlertDialog.Builder(getContext()).
                                setTitle("信息").
                                setMessage("请说明业务情况").
                                setIcon(R.drawable.ic_launcher).
                                setPositiveButton("确定", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        AddDemand();
                                    }
                                }).
                                create();
                        alertDialog.show();
                        return false;
                    }

                        Intent intent = new Intent();
                        intent.putExtra("id", 0);
                        intent.putExtra("category", "other");
                        intent.setClass(getContext(), MoveActivity.class);
                        startActivityForResult(intent, ADD_UPDATE_CODE);
                }


                if (item.getItemId() == R.id.nav_add_member) {
                    Intent intent = new Intent();
                    intent.setClass(getContext(), ConfirmOrgActivity.class);
                    startActivityForResult(intent, MY_ADDMEMBER_CODE);
                }

//                if (item.getItemId() == R.id.nav_add_user) {
//                    Intent intent = new Intent();
//                    intent.setClass(getContext(), InviteActivity.class);
//                    startActivity(intent);
//                }

                if (item.getItemId() == R.id.nav_add_partner) {
                    if (!WoyaoooApplication.hasLogin) {
                        Intent intent = new Intent();
                        intent.setClass(getContext(), RegisterActivity.class);
                        startActivityForResult(intent, MYREGISTER_CODE);
                        return false;
                    }
//                    mListener.onTabChance(R.id.cooperate);
                    Intent intent = new Intent();
                    intent.setClass(getContext(), RelationActivity.class);
                    intent.putExtra("is_new", true);
                    startActivity(intent);
                }
                return false;
            }
        });

        matchDemand = (TextView) theview.findViewById(R.id.id_demand_title);

        matchDemand.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switchDemands();
            }
        });


        summaryText = (TextView) theview.findViewById(R.id.id_chances_summary);
        sloganText = (TextView) theview.findViewById(R.id.id_chances_slogan);

        orderTxt = (TextView) theview.findViewById(R.id.id_order_text);
        statusTxt = (TextView) theview.findViewById(R.id.id_status_text);
        mViewPager = (android.support.v4.view.ViewPager) theview.findViewById(R.id.viewpager);

        tempShareImageView = (ImageView) theview.findViewById(R.id.id_temp_forshare);

        chanceAll = (LinearLayout) theview.findViewById(R.id.id_chance_all);

        emptyAll = (FrameLayout) theview.findViewById(R.id.id_chance_empty);

        messageBtn = (Button) theview.findViewById(R.id.chance_msg);
        main_chance = (CardView) theview.findViewById(R.id.chance_main);


        personBtn = (Button) theview.findViewById(R.id.id_chance_personal);

        personBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CompleteAccount();
            }
        });

        addDemandBtn = (Button) theview.findViewById(R.id.id_chances_add_demand);

        addDemandBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AddDemand();
            }
        });


        modifyPreferBtn = (Button) theview.findViewById(R.id.id_chances_prefer);

        modifyPreferBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                modifyPrefer();
            }
        });


        matchBtn = (Button) theview.findViewById(R.id.chance_match);

        matchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                Calendar calendar = Calendar.getInstance();
//                calendar.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
////                        calendar.add(Calendar.DATE, 1);
//                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                chance.setDisplaydate(formatter.format(calendar.getTime()) );

                Calendar calendar = Calendar.getInstance();
                calendar.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
//                        calendar.add(Calendar.DATE, 1);
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

                getChances("");
            }
        });

//        serviceText = (TextView) theview.findViewById(R.id.service_content);
//        publishBtn = (LinearLayout) theview.findViewById(R.id.id_add_demand_action);
//
//
//        publishBtn.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//
//                loadUserBasic();
//                if (!WoyaoooApplication.hasLogin) {
//                    Intent intent = new Intent();
//                    intent.setClass(getContext(), RegisterActivity.class);
//                    startActivityForResult(intent, MYREGISTER_CODE);
//                    return;
//                }
//
//                if (WoyaoooApplication.displayname.equals("")) {
//                    CompleteAccount();
//                    return;
//                }
//                AddDemand();
//            }
//        });




//        categoryBtn = (LinearLayout) theview.findViewById(R.id.id_match_category);
//
//        categoryBtn.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (!WoyaoooApplication.hasLogin) {
//                    Intent intent = new Intent();
//                    intent.setClass(getContext(), RegisterActivity.class);
//                    startActivityForResult(intent, MYREGISTER_CODE);
//                    return;
//                }
//
//                modifyCategory();
//            }
//
//        });
        moreBtn = (LinearLayout) theview.findViewById(R.id.id_match_more);

        moreBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!WoyaoooApplication.hasLogin) {
                    Intent intent = new Intent();
                    intent.setClass(getContext(), RegisterActivity.class);
                    startActivityForResult(intent, MYREGISTER_CODE);
                    return;
                }
                getChances("more");

            }

        });

        markBtn = (LinearLayout) theview.findViewById(R.id.id_chance_mark);

        markImageView = (ImageView) theview.findViewById(R.id.id_chance_mark_image);
        applyImageView = (ImageView) theview.findViewById(R.id.id_chance_apply_image);

        markBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadUserBasic();
                if (!WoyaoooApplication.hasLogin) {
                    Intent intent = new Intent();
                    intent.setClass(getContext(), RegisterActivity.class);
                    startActivityForResult(intent, MYREGISTER_CODE);
                    return;
                }


                markIt();

            }
        });

        shareBtn = (LinearLayout) theview.findViewById(R.id.id_chance_refer);


        shareBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadUserBasic();
                if (!WoyaoooApplication.hasLogin) {
                    Intent intent = new Intent();
                    intent.setClass(getContext(), RegisterActivity.class);
                    startActivityForResult(intent, MYREGISTER_CODE);
                    return;
                }


                referIt();

            }
        });

        goutongBtn = (LinearLayout) theview.findViewById(R.id.id_goutong);

        goutongBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadUserBasic();
                if (!WoyaoooApplication.hasLogin) {
                    Intent intent = new Intent();
                    intent.setClass(getContext(), RegisterActivity.class);
                    startActivityForResult(intent, MYREGISTER_CODE);
                    return;
                }


                if (WoyaoooApplication.displayname.equals("")) {
                    CompleteAccount();
                    return;
                }


                startTalk();

            }
        });

        applyBtn = (LinearLayout) theview.findViewById(R.id.id_apply);

        applyBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!WoyaoooApplication.hasLogin) {
                    Intent intent = new Intent();
                    intent.setClass(getContext(), RegisterActivity.class);
                    startActivityForResult(intent, MYREGISTER_CODE);
                    return;
                }

                ChanceSummary chance = chances.get(current);

                if (!chance.getStatus().equals("apply")) {
//                    startTalk();
////
////                    Intent intent = new Intent();
////                    intent.putExtra("mid", 0);
////                    intent.putExtra("id", chance.getPid());
////                    intent.setClass(getContext(), RelationActivity.class);
////                    startActivity(intent);
//                } else {
                    if (chance.getObject_status().equals("apply")) {
                        applyIt(0,"");
                    } else {
                        if (uvm.getUser().getDisplayname().equals("")) {
                            CompleteAccount();
                        } else {
                            confirmApply();
                        }
                    }
                }

            }
        });


        applyText = (TextView) theview.findViewById(R.id.id_apply_text);

        chanceAll.setVisibility(View.INVISIBLE);
        emptyAll.setVisibility(View.VISIBLE);

        initData();




        return theview;
    }

    private void startTalk(){
        ChanceSummary chance = chances.get(current);

        if (chance.getMessage_num() == 0){
            messageBtn.setVisibility(View.GONE);
        }else{
            messageBtn.setVisibility(View.VISIBLE);
            messageBtn.setText( chance.getMessage_num() +"");
        }

        Intent intent = new Intent();
        intent.putExtra("from", "main");
        intent.putExtra("id", chance.getPid());
        intent.putExtra("type", "match");
        intent.setClass(getContext(), TalkActivity.class);
        startActivity(intent);


    }
    private Integer addUpdateChoice= 0;

    private void markIt() {

        if (uvm.getUser().getDisplayname().equals("")) {

            new AlertDialog.Builder(getContext())
                    .setTitle("信息")
                    .setMessage("请完善个人资料")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            CompleteAccount();
                        }
                    }).create().show();
            return;
        }



        final ChanceSummary chance = chances.get(current);
        chance.setMarked(!chance.getMarked());

        AsyncTask<Void, Void, BaseResponse> task =
                new AsyncTask<Void, Void, BaseResponse>() {
                    @Override
                    protected BaseResponse doInBackground(Void... params) {
                        ChanceService svc = ServiceFactory.get(ChanceService.class);

                        Call<BaseResponse> responseCall = svc.mark(userId,chance.getPid(),chance.getId(),chance.getMarked().toString().toLowerCase());
                        try {
                            BaseResponse response = responseCall.execute().body();
                            return  response;
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(final BaseResponse response) {

                        if ( response != null) {
                            if (response.isSuccess()) {
                                if  (chance.getMarked()){
                                    markImageView.setImageResource(R.drawable.love_accent1);
                                }else{
                                    markImageView.setImageResource(R.drawable.markaccent1);
                                }
                            }else{
                                Toast.makeText(getContext(),response.getMessage(),Toast.LENGTH_SHORT).show();
                            }

                        }else{
                            Toast.makeText(getContext(),"处理失败",Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    protected void onCancelled() {

                    }
                };
        task.execute((Void) null);

    }

    private void referIt(  ){

        if (uvm.getUser().getDisplayname().equals("")) {

            new AlertDialog.Builder(getContext())
                    .setTitle("信息")
                    .setMessage("请完善个人资料")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            CompleteAccount();
                        }
                    }).create().show();
            return;
        }

        ChanceSummary chance = chances.get(current);
        Intent intent = new Intent();
        intent.setClass(getContext(), ReferActivity.class);
        intent.putExtra("title", chance.getTitle());

        Manager theManager = chance.getManager();


        intent.putExtra("description", chance.getDescription() + "\n " +theManager.getRole() + "\n " + theManager.getLocation() + "\n " +  theManager.getDisplayname() );

        intent.putExtra("id", chance.getId());

        Picasso.with(getContext())
                .load(chance.getImage())
                .into(tempShareImageView );

        tempShareImageView.setDrawingCacheEnabled(true);
        Bitmap bitmap = Bitmap.createBitmap(tempShareImageView.getDrawingCache());
        tempShareImageView.setDrawingCacheEnabled(false);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        int options = 90;
        while (baos.toByteArray().length / 1024 > 32) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset(); // 重置baos即清空baos
            bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;// 每次都减少10
        }
        intent.putExtra("photo_bmp", baos.toByteArray());

        startActivity(intent);
    }
    private void initData() {

        loadHows();
        loadProfile();

        Uri uri = getActivity().getIntent().getData();
        if (uri != null) {
            try {
//                StringBuilder sb = new StringBuilder();
//                // 唤起链接
//                sb.append("string : ").append(getActivity().getIntent().getDataString()).append("\n");
//                sb.append("scheme : ").append(uri.getScheme()).append("\n");
//                sb.append("host : ").append(uri.getHost()).append("\n");
//                sb.append("port : ").append(uri.getPort()).append("\n");
//                sb.append("path : ").append(uri.getPath()).append("\n");
//                // 接收唤起的参数
//                sb.append("bid : ").append(uri.getQueryParameter("bid")).append("\n");
//                sb.append("rid : ").append(uri.getQueryParameter("rid")).append("\n");

//                Common.alert(this, sb.toString());

                String bid = uri.getQueryParameter("bid");
                String rid = uri.getQueryParameter("rid");

                if (bid != null) {

                    Intent intent = new Intent();
                    intent.putExtra("from", "main");
                    intent.putExtra("id",  Integer.parseInt(bid ) );
                    intent.setClass(getContext(), ChanceViewActivity.class);
                    startActivity(intent);

                }


            } catch (Exception e) {
                e.printStackTrace();
            }
        }




        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        today = formatter.format(calendar.getTime());

    }

    public  void modifyDemand(){
        if (!WoyaoooApplication.hasLogin){
            Intent intent = new Intent();
            intent.setClass(getContext(), RegisterActivity.class);
            startActivityForResult(intent,MYREGISTER_CODE);
            return;
        }


        Intent intent = new Intent();
        intent.putExtra("from", "chance"  );
        intent.putExtra("is_new", false);
        intent.putExtra("id", uvm.getUser().getDemand_id()  );
        intent.setClass(getContext(), DemandNewActivity.class);
        startActivityForResult(intent, MODIFY_DEMAND_CODE);
    }

    public  void AddDemand(){
        if (!WoyaoooApplication.hasLogin){
            Intent intent = new Intent();
            intent.setClass(getContext(), RegisterActivity.class);
            startActivityForResult(intent,MYREGISTER_CODE);
            return;
        }
        if ( uvm.getUser().getDisplayname().equals("") ){
            Dialog alertDialog = new AlertDialog.Builder(getContext()).
                    setTitle("信息").
                    setMessage("请填写个人资料").
                    setIcon(R.drawable.ic_launcher).
                    setPositiveButton("确定", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            CompleteAccount();
                        }
                    }).
                    create();
            alertDialog.show();
            return ;
        }

        Intent intent = new Intent();
        intent.putExtra("from", "chance"  );
        intent.putExtra("is_new", true);
        intent.setClass(getContext(), DemandNewActivity.class);
        startActivityForResult(intent, ADD_DEMAND_CODE);
    }

    public  void modifyPrefer() {
        Intent intent = new Intent();
        intent.putExtra("from", "chance"  );
        intent.setClass(getContext(), PreferActivity.class);
        startActivityForResult(intent ,COMPLETE_PREFER_CODE);
    }

    public  void CompleteLocation() {
        Intent intent = new Intent();
        intent.putExtra("from", "chance");
        intent.setClass(getContext(), ConfirmLocation.class);
        startActivityForResult(intent, COMPLETE_LOCATION_CODE);
    }

    public  void CompleteAccount(){
        if (!WoyaoooApplication.hasLogin){
            Intent intent = new Intent();
            intent.setClass(getContext(), RegisterActivity.class);
            startActivityForResult(intent,MYREGISTER_CODE);
            return;
        }
        Intent intent = new Intent();
        intent.putExtra("from", "chance"  );
        intent.setClass(getContext(), AccountActivity.class);
        startActivityForResult(intent, COMPLETE_ACCOUNT_CODE);
    }
    public void renderVerify(){
        if (!WoyaoooApplication.hasLogin){
            Intent intent = new Intent();
            intent.setClass(getContext(), RegisterActivity.class);
            startActivityForResult(intent,MYREGISTER_CODE);
            return;
        }
        Intent intent = new Intent();
        intent.setClass(getContext(), VerifyActivity.class);
        startActivityForResult(intent, COMPLETE_VEFIFY_CODE);
    }

    private void renderMoney( ){
        if (!WoyaoooApplication.hasLogin){
            Intent intent = new Intent();
            intent.setClass(getContext(), RegisterActivity.class);
            startActivityForResult(intent,MYREGISTER_CODE);
            return;
        }
        Intent intent = new Intent();
        intent.putExtra("money", 100.0);
        intent.setClass(getContext(), MoneyActivity.class);
        startActivity(intent);
    }

    private void viewIt( final Integer pid) {


        AsyncTask<Void, Void, BaseResponse> loadTask =
                new AsyncTask<Void, Void, BaseResponse>() {
                    @Override
                    protected BaseResponse doInBackground(Void... params) {
                        ChanceService svc = ServiceFactory.get(ChanceService.class);
                        Call<BaseResponse> responseCall = svc.view(userId, pid);
                        try {
                            BaseResponse response = responseCall.execute().body();
                            return response;
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(final BaseResponse response) {

                    }
                };
        loadTask.execute((Void) null);
    }


    private void loadProfile() {

        final String version = Common.getCurrentVersion(getContext());

        AsyncTask<Void, Void, ProfileResponse> loadTask =
                new AsyncTask<Void, Void, ProfileResponse>() {
                    @Override
                    protected ProfileResponse doInBackground(Void... params) {
                        AccountService svc = ServiceFactory.get(AccountService.class);
                        Call<ProfileResponse> responseCall = svc.getProfile(userId, "android",version);
                        try {
                            ProfileResponse response = responseCall.execute().body();
                            return response;
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(final ProfileResponse response) {
                        if (response != null && response.isSuccess()) {
                            Application application = getActivity().getApplication();
                            User user = response.getContent();

                            uvm.initUser( user);

                            SharedPreferences shared = application.getSharedPreferences("login", MODE_PRIVATE);

                            SharedPreferences.Editor editor = shared.edit();
                            editor.putInt("demand_id", user.getDemand_id());
                            editor.putString("key", user.getKey());
                            editor.putString("displayname", user.getDisplayname());
                            editor.putString("snailview", user.getSnailview());
                            editor.putString("location", user.getLocation());
                            editor.putString("title", user.getTitle());
                            editor.putString("business", user.getBusiness());
                            editor.putString("business_name", user.getBusiness_name());
                            editor.putInt("member_id", user.getMember_id());
                            editor.putString("mobile", user.getMobile());
                            editor.commit();


                            WoyaoooApplication.key = user.getKey();
                            WoyaoooApplication.snailview = user.getSnailview();
                            WoyaoooApplication.displayname = user.getDisplayname();
                            WoyaoooApplication.location = user.getLocation();
                            WoyaoooApplication.title = user.getTitle();
                            WoyaoooApplication.member_id = user.getMember_id();
                            WoyaoooApplication.demand_id = user.getDemand_id();


                            mListener.onMessage(user.getChance_num(), "chance" );
                            mListener.onMessage(user.getMessage_num(), "talk" );
                            mListener.onMessage(user.getCooperate_num(), "cooperate" );
                            mListener.onMessage(user.getInterest_num(), "interest" );
//                            mListener.onMessage(user.getMember_num(), "member" );
//                            mListener.onMessage(user.getPerson_num(), "person" );

                            summaryText.setText( user.getSummary());
//                            serviceText.setText( user.getService());
                            sloganText.setText( user.getSlogan());

                            matchDemand.setText( user.getDemand_title());

//                            if ( user.getDisplayname().equals("") ||  user.getCategory().equals("") || user.getDemand_id() == 0){
//                                showEmpty();
//                            }else{
                            if ( chances.size() == 0 ) {
                                getChances("");
                            }
//                            }
                        }
                    }
                };
        loadTask.execute((Void) null);
    }


    public void getChances(final String act) {


        ConnectivityManager connMgr = (ConnectivityManager)
                getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo == null || !networkInfo.isConnected()) {
            Dialog alertDialog = new AlertDialog.Builder(getContext()).
                    setTitle("错误").
                    setMessage("没有网络，请检查设置！").
                    setIcon(R.drawable.ic_launcher).
                    setPositiveButton("确定", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            getChances("");
                        }
                    }).
                    create();
            alertDialog.show();

            return;
        }

        if (loading) {
//            Toast.makeText(this, "正在加载...", Toast.LENGTH_SHORT).show();
            return;
        }

        progressDialog = new ProgressDialog(getContext());
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("加载···");
        progressDialog.show();
        loading = true;
        String login = "false";
        if (WoyaoooApplication.hasLogin) {
            login = "true";
        }
        final String loginstr = login;

        AsyncTask<Void, Void, GetNextChancesResponse> task = new AsyncTask<Void, Void, GetNextChancesResponse>() {
            @Override
            protected GetNextChancesResponse doInBackground(Void... params) {
                ChanceService svc = ServiceFactory.get(ChanceService.class);
                Call<GetNextChancesResponse> responseCall = svc.nexts(userId,act,loginstr);
                GetNextChancesResponse ret = null;
                try {
                    ret = responseCall.execute().body();
                } catch (IOException e) {
                    e.printStackTrace();
                    ret = null;
                }
                return ret;
            }

            @Override
            protected void onPostExecute(final GetNextChancesResponse resp) {
                progressDialog.dismiss();
                loading = false;
                if (resp != null) {

                    if (resp.isSuccess()) {
                        chances = resp.getContent().getItems();
                        if (!resp.getMessage().equals(""))
                            Common.alert(getContext(), resp.getMessage());

                        if (chances != null) {
                            if (!resp.getContent().getCaption().equals("")) {
                                toolbar.setTitle(resp.getContent().getCaption());
                            }
                            renderChances();
                            return;
                        } else {
                            Common.alert(getContext(), "获取机会失败，请重试！");
                        }
                    }else{

                        if (resp.getType().equals("info")){
                            Dialog alertDialog = new AlertDialog.Builder(getContext()).
                                    setTitle("信息").
                                    setMessage(resp.getMessage()).
                                    setIcon(R.drawable.ic_launcher).
                                    setPositiveButton("确定", new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {

                                        }
                                    }).
                                    create();
                            alertDialog.show();
                            return;

                        }

                        if (resp.getType().equals("must")){

                            if ( resp.getMessage().equals("")){
                                handleCondition( resp);
                                return;
                            }

                            Dialog alertDialog = new AlertDialog.Builder(getContext()).
                                    setTitle("信息").
                                    setMessage(resp.getMessage()).
                                    setIcon(R.drawable.ic_launcher).
                                    setPositiveButton("确定", new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            handleCondition( resp);
                                        }
                                    }).
                                    create();
                            alertDialog.show();
                            return;
                        }

                        if (resp.getType().equals("optional")){
                            Dialog alertDialog = new AlertDialog.Builder(getContext()).
                                    setTitle("信息").
                                    setMessage(resp.getMessage()).
                                    setIcon(R.drawable.ic_launcher).
                                    setPositiveButton("确定", new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            handleCondition( resp);
                                        }
                                    }).
                                    setNegativeButton("取消", new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {

                                        }
                                    }).
                                    create();
                            alertDialog.show();
                            return;
                        }


                    }
                } else {

                    Common.showSnack(getContext(), matchBtn, "请检查网络后重试！");

                }


            }

            @Override
            protected void onCancelled() {
                progressDialog.dismiss();
                loading = false;
                Common.showSnack(getContext(), matchBtn, "没有成功获取新机会！");

            }
        };
        task.execute((Void) null);

    }

    private void renderChances( ){

        if (chances.size() >0 ){
            chanceAll.setVisibility(View.VISIBLE);
            emptyAll.setVisibility(View.INVISIBLE);
        }else{
            chanceAll.setVisibility(View.INVISIBLE);
            emptyAll.setVisibility(View.VISIBLE);
        }

        mPagerAdapter = new ChanceSummaryAdapter(getContext(),chances);


        mPagerAdapter.setChangedHandler(new ChanceSummaryAdapter.Changed() {
            @Override
            public void view(Integer pos) {
                if (current != pos ) {

                    current = pos;
                    ChanceSummary chance = chances.get(pos);
                    applyText.setText(chance.getApply_text());

                    if (chance.getMessage_num() == 0){
                        messageBtn.setVisibility(View.GONE);
                    }else{
                        messageBtn.setVisibility(View.VISIBLE);
                        messageBtn.setText( chance.getMessage_num() +"");
                    }

                    if  (chance.getMarked()){
                        markImageView.setImageResource(R.drawable.love_accent1);
                    }else{
                        markImageView.setImageResource(R.drawable.markaccent1);
                    }

                    if (chance.getStatus().equals("apply")){
                        applyImageView.setImageResource(R.drawable.hezuored);
                        applyText.setTextColor(ContextCompat.getColor(getContext(), R.color.red));
                    }else{
                        applyImageView.setImageResource(R.drawable.hezuoaccent1);
                        applyText.setTextColor(ContextCompat.getColor(getContext(), R.color.colorAccent1));
                    }

                    applyText.setText( chance.getApply_text());

                    orderTxt.setText((pos + 1) + "/" + chances.size());
                    statusTxt.setText( chance.getStatus_text());

                    if (!chance.getMessage().equals("")) {
                        new AlertDialog.Builder(getContext())
                                .setTitle("信息")
                                .setMessage(chance.getMessage())
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                    }
                                }).create().show();
                    }

                    if (chance.getDisplaydate() == null) {
                        chance.setDisplaydate(new Date());
                        viewIt(chance.getPid());
                    }
                    setMessageNum();


                }

                Boolean hasUnread = false;
                for ( int j = 0 ; j < chances.size(); j=j+1){

                    if ( chances.get(j).getDisplaydate() == null){
                        hasUnread = true;
                        break;
                    }
                }

//                if (!hasUnread &&  !askedMore  ) {
//                    askedMore = true;
//                        new AlertDialog.Builder(getContext())
//                                .setTitle("信息")
//                                .setMessage("需要更多的机会吗？")
//                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                                    @Override
//                                    public void onClick(DialogInterface dialog, int which) {
//                                        getChances("more");
//                                    }
//                                })
//                                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
//                                    @Override
//                                    public void onClick(DialogInterface dialog, int which) {
//
//                                    }
//                                }).create().show();
//                }
//
//                    if (uvm.getUser().getDemand_id() == 0 ){
//
//                        new AlertDialog.Builder(getContext())
//                                .setTitle("信息")
//                                .setMessage("请发布业务，稳定匹配合作")
//                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                                    @Override
//                                    public void onClick(DialogInterface dialog, int which) {
//                                        AddDemand();
//                                    }
//                                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
//
//                            }
//                        }).create().show();
//                        return;
//                    }
//                }else{
//                    Toast.makeText(getContext(),"每天把握10个合作机会",Toast.LENGTH_LONG);
//                }


            }
        });

        mViewPager.setAdapter( mPagerAdapter);

        if (chances.size() >0 ) {
            current = 0;

            for ( int j = 0 ; j < chances.size(); j=j+1){

                if ( chances.get(j).getDisplaydate() == null){
                    current = j;
                    break;
                }
            }
            mViewPager.setCurrentItem(current);
            try {
                Field field = mViewPager.getClass().getField("mCurItem");//参数mCurItem是系统自带的
                field.setAccessible(true);
                field.setInt(mViewPager,current);
            }catch (Exception e){
                e.printStackTrace();
            }
            mPagerAdapter.notifyDataSetChanged();


        //https://blog.csdn.net/myGFZ/article/details/53515506
            ChanceSummary chance = chances.get(current);
            applyText.setText(chance.getApply_text());

            if (chance.getMessage_num() == 0){
                messageBtn.setVisibility(View.GONE);
            }else{
                messageBtn.setVisibility(View.VISIBLE);
                messageBtn.setText( chance.getMessage_num() +"");
            }

            if  (chance.getMarked()){
                markImageView.setImageResource(R.drawable.love_accent1);
            }else{
                markImageView.setImageResource(R.drawable.markaccent1);
            }

            if (chance.getStatus().equals("apply")){
                applyImageView.setImageResource(R.drawable.hezuored);
                applyText.setTextColor(ContextCompat.getColor(getContext(), R.color.red));
            }else{
                applyImageView.setImageResource(R.drawable.hezuoaccent1);
                applyText.setTextColor(ContextCompat.getColor(getContext(), R.color.colorAccent1));
            }
            statusTxt.setText( chance.getStatus_text());
            orderTxt.setText( ( current +1) +"/" + chances.size());

            if (!chance.getMessage().equals("")) {
                new AlertDialog.Builder(getContext())
                        .setTitle("信息")
                        .setMessage(chance.getMessage())
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        }).create().show();
            }

            if (chance.getDisplaydate() == null) {
                chance.setDisplaydate(new Date());
                viewIt(chance.getPid());
            }
        }
        setMessageNum();


    }

    private void setMessageNum(){
        Integer unread = 0;
        for ( ChanceSummary one : chances){
            if ( one.getDisplaydate() == null){
                unread +=1 ;
            }
        }
        mListener.onMessage(unread, "chance" );



    }

    private void handleCondition(GetNextChancesResponse resp){

        if (chances.size() > 0 ) {
            chanceAll.setVisibility(View.VISIBLE);
            emptyAll.setVisibility(View.INVISIBLE);
        }else{
            chanceAll.setVisibility(View.INVISIBLE);
            emptyAll.setVisibility(View.VISIBLE);
        }

        Intent intent = new Intent();
        switch ( resp.getCondition()) {
            case "register":
                intent.setClass(getContext(), RegisterActivity.class);
                startActivityForResult(intent,MYREGISTER_CODE);
                return;
            case "login":
                intent.setClass(getContext(), LoginActivity.class);
                startActivityForResult(intent,MY_LOGIN_CODE);
                return;
            case "position":
                TryGetCurrentLocation();
                return;
            case "upgrade":
                apk_path = resp.getContent().getDescription().trim();
                if ( checkStoragePermission() ) {
                    showDownloadDialog();
                }
                return;
            case "verify" :
                renderVerify();
                break;
            case "charge" :
                renderMoney();
                break;
            case "personal":
                CompleteAccount();
                break;
            case "demand":
                AddDemand();
                break;
            case "member":
                AddMember();
                break;
            case "location":
                CompleteLocation();
                break;

            case "category":
                modifyCategory();
                break;
            case "modifydemand":
                modifyDemand();
                break;
            case "prefer":
                modifyPrefer();
                break;
            case "empty":
                showEmpty();
                break;
            default :
                Log.i("ChancesFragment","nothing");
        }


        if (uvm != null) {
            mListener.onMessage(0,"chance");

        }

    }

    private void AddMember(){
        Intent intent = new Intent();
        intent.putExtra("from","mymember");
        intent.putExtra("id",0);

        intent.setClass(getContext(), ConfirmOrgActivity.class);

        startActivityForResult(intent, ADD_MEMBER_CODE);
    }

    private void modifyCategory(){
        Intent intent = new Intent();
        intent.putExtra("from", "chance"  );
        KeyValueList kvl = new KeyValueList();
        kvl.setContent( uvm.getUser().getCategory_list() );
        intent.putExtra("category_list", kvl  );
        intent.setClass(getContext(), FilterCategory.class);
        startActivityForResult(intent ,COMPLETE_CATEGORY_CODE);
    }
    public  void TryGetCurrentLocation() {

        if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions( new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, ASKLOCATION_CODE);
        } else {
            getCurrentLocation();
        }
    }

    public  void getCurrentLocation() {
        try {
            if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }

            LocationManager mLocationManager = (LocationManager) getActivity().getApplication().getSystemService(LOCATION_SERVICE);
            List<String> all_providers = mLocationManager.getProviders(true);
            Location bestLocation = null;
            for (String provider : all_providers) {
                Location l = mLocationManager.getLastKnownLocation(provider);
                if (l == null) {
                    continue;
                }
                if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
                    // Found best last known location: %s", l);
                    bestLocation = l;
                }
            }

            if (bestLocation != null) {
                String longitude = bestLocation.getLongitude() + "";
                String latitude = bestLocation.getLatitude() + "";
                changeProfile("lnglat", longitude +"#" +latitude);
                return;
            }
        }catch (Exception e) {
            Toast.makeText(getContext(),"稳定匹配合作，请授权访问定位。",Toast.LENGTH_LONG);
        }
        CompleteLocation();

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUEST_STORAGE:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED ) {
                    showDownloadDialog();
//                    new AlertDialog.Builder(getContext())
//                            .setTitle("下载新版本")
//                            .setMessage("")
//                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                                @Override
//                                public void onClick(DialogInterface dialog, int which) {
//                                    dialog.dismiss();
//                                    showDownloadDialog();
//                                    return;
//                                }
//                            }).create().show();
                } else {
                    new AlertDialog.Builder(getContext())
                            .setTitle("授权访问存储设备")
                            .setMessage("请授权，才可以升级")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            }).create().show();

                }
                // getBatch
                break;
            case ASKLOCATION_CODE:
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    getCurrentLocation();

                } else {
                    CompleteLocation();
//                    Log.i("woyaooo", "onRequestPermissionsResult:  fail");
//                    Dialog alertDialog = new AlertDialog.Builder(RegisterActivity.this).
//                            setTitle("信息").
//                            setMessage("为您整合附近的资源，请授权访问定位").
//                            setIcon(R.drawable.ic_launcher).
//                            setPositiveButton("确定", new DialogInterface.OnClickListener() {
//
//                                @Override
//                                public void onClick(DialogInterface dialog, int which) {
//
//                                }
//                            }).
//                            create();
//                    alertDialog.show();
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                }
                break;
            case ASKCONTACTS_CODE: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                    getContacts();
                } else {
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                }
                return;
                // other 'case' lines to check for other
                // permissions this app might request
            }
        }
    }


    private void loadUserBasic(){
        Application application = getActivity().getApplication();
        SharedPreferences shared = application.getSharedPreferences("login", MODE_PRIVATE);

        try {
            WoyaoooApplication.hasLogin = shared.getBoolean("logged", false);
            WoyaoooApplication.userId = shared.getInt("userId", 0);
            WoyaoooApplication.displayname = shared.getString("displayname", "");;
            WoyaoooApplication.location = shared.getString("location", "");
            WoyaoooApplication.title = shared.getString("title", "");
            WoyaoooApplication.snailview = shared.getString("snailview", "");
            WoyaoooApplication.demand_id = shared.getInt("demand_id",0);
        }catch (Exception e){

        }

    }
    @Override
    public void onResume() {
        super.onResume();
        loadUserBasic();
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String theday = formatter.format(calendar.getTime());
        if (!theday.equals(today)  ) {
            uvm.getUser().businessChanged = true;
            uvm.getUser().cooperateChanged = true;
            today = theday;
            loadProfile();
        }

//        else{
//            User user = uvm.getUser();
//            if ( user.getDisplayname().equals("") ||  user.getCategory().equals("") || user.getDemand_id() == 0){
//                showEmpty();
//            }
//        }


    }

    public void  checkInfoComplete(){
        User user = uvm.getUser();
        if ( user.getDisplayname().equals("") ||  user.getCategory().equals("") || user.getDemand_id() == 0){
            showEmpty();
        }
    }
    private void showEmpty(  ) {
        User user = uvm.getUser();

        if ( user!= null) {
            if (!user.getDisplayname().equals("")) {
                personBtn.setTextColor(ContextCompat.getColor(getContext(), R.color.colorSubTitleText));
            } else {
                personBtn.setTextColor(ContextCompat.getColor(getContext(), R.color.colorTextPrimary));
            }

            if (!user.getCategory().equals("")) {
                modifyPreferBtn.setTextColor(ContextCompat.getColor(getContext(), R.color.colorSubTitleText));
            } else {
                modifyPreferBtn.setTextColor(ContextCompat.getColor(getContext(), R.color.colorTextPrimary));
            }

            if (user.getDemand_id() > 0) {
                addDemandBtn.setTextColor(ContextCompat.getColor(getContext(), R.color.colorSubTitleText));
            } else {
                addDemandBtn.setTextColor(ContextCompat.getColor(getContext(), R.color.colorTextPrimary));
            }
        }
        chanceAll.setVisibility(View.INVISIBLE);
        emptyAll.setVisibility(View.VISIBLE);

        toolbar.setTitle("我要合作网");
    }
    int yourChoice = 0 ;
    private void confirmApply(){

        final String[] items =  (String[])howList.toArray(new String[0]);

        AlertDialog.Builder singleChoiceDialog =
                new AlertDialog.Builder(getContext());
        singleChoiceDialog.setTitle("请选择合作方式");
        // 第二个参数是默认选项，此处设置为0
        singleChoiceDialog.setSingleChoiceItems(items, yourChoice,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        yourChoice = which;
                    }
                });
        singleChoiceDialog.setPositiveButton("确 定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        applyIt( 0,items[yourChoice]);
                    }
                });
        singleChoiceDialog.setNegativeButton("取 消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
        singleChoiceDialog.show();
    }


    private void loadHows(){
        AsyncTask<Void,Void, GetChildHowResponse> task =
                new AsyncTask<Void, Void, GetChildHowResponse>() {
                    @Override
                    protected GetChildHowResponse doInBackground(Void... params) {
                        HowService svc = ServiceFactory.get(HowService.class);
                        Call<GetChildHowResponse> responseCall = svc.getChildHow("all",WoyaoooApplication.userId,"");
                        try {
                            GetChildHowResponse response = responseCall.execute().body();
                            return response;
                        } catch (IOException e) {
                            e.printStackTrace();
                            return null;
                        }
                    }
                    @Override
                    protected void onPostExecute(final GetChildHowResponse response) {

                        ArrayList<How> hows = response.getHowList();
                        howList.clear();
                        for( How hw : hows){
                            howList.add(hw.getName());
                        }
                    }
                    @Override
                    protected void onCancelled() {
                        progressDialog.dismiss();
                    }
                };
        task.execute();
    }
    private int demandChoice =0 ;
    private void switchDemands(){

        AsyncTask<Void, Void, GetMyDemandResponse> task =new AsyncTask<Void, Void, GetMyDemandResponse>() {
            @Override
            protected GetMyDemandResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<GetMyDemandResponse> responseCall = svc.getMyDemand(WoyaoooApplication.userId, "false");
                try {
                    GetMyDemandResponse response = responseCall.execute().body();
                    return response;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
            @Override
            protected void onPostExecute(final GetMyDemandResponse response) {

                final List<DemandSummary> demands = response.getContent();
                ArrayList<String> demandList = new ArrayList<String>();
                final ArrayList<Integer> demandIdList = new ArrayList<Integer>();
                for ( DemandSummary ds : demands){
                    demandList.add( ds.getTitle());
                    demandIdList.add(ds.getId());
                }

                demandList.add( "新建业务");
                demandIdList.add(0);
                final String[] items = demandList.toArray(new String[0]);

                AlertDialog.Builder singleChoiceDialog =
                        new AlertDialog.Builder(getContext());
                singleChoiceDialog.setTitle("选择匹配的业务");
                // 第二个参数是默认选项，此处设置为0
                singleChoiceDialog.setSingleChoiceItems(items, demandChoice,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                demandChoice = which;
                            }
                        });
                singleChoiceDialog.setPositiveButton("确 定",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (demandIdList.get(demandChoice) == 0 )
                                {
                                    AddDemand();
                                }else {
                                    matchDemand.setText(items[demandChoice]);
                                    changeProfile("demand_id", demandIdList.get(demandChoice) + "");
                                }
                            }
                        });
                singleChoiceDialog.setNegativeButton("取 消",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        });
                singleChoiceDialog.show();

            }
            @Override
            protected void onCancelled() {

            }
        };
        task.execute((Void)null);

    }



    private void applyIt( final Integer demand_id ,final String how) {
        if (!WoyaoooApplication.hasLogin){
            Intent intent = new Intent();
            intent.setClass(getContext(), RegisterActivity.class);
            startActivityForResult(intent,MYREGISTER_CODE);
            return;
        }

        final ChanceSummary chance = chances.get(current);

        AsyncTask<Void, Void, ApplyResponse> task =
                new AsyncTask<Void, Void, ApplyResponse>() {
                    boolean bizComplete = false;

                    @Override
                    protected ApplyResponse doInBackground(Void... params) {
                        ChanceService svc = ServiceFactory.get(ChanceService.class);

                        Call<ApplyResponse> responseCall = svc.apply(userId,how, chance.getId(),demand_id  ,chance.getPid(),0);
                        try {
                            ApplyResponse response = responseCall.execute().body();
                            return  response;
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(final ApplyResponse response) {
                        progressDialog.dismiss();
                        if ( response != null) {
                            if (response.isSuccess()) {

                                uvm.getUser().cooperateChanged = true;
//                                Common.alert( getContext(), response.getMessage());

                                statusTxt.setText( response.getMessage());
                                chance.setStatus("apply");
                                if (!response.getMessage().equals("")) {
                                    Toast.makeText(getContext(), response.getMessage(), Toast.LENGTH_LONG).show();
                                }
                                applyImageView.setImageResource(R.drawable.hezuored);
                                applyText.setTextColor(ContextCompat.getColor(getContext(), R.color.red));
//    c                            startTalk();
//                                if (response.getCondition().equals("relation")) {
//                                    Intent intent = new Intent();
//                                    intent.putExtra("mid", 0 );
//                                    intent.putExtra("id", chance.getPid());
//                                    intent.setClass(getContext(), RelationActivity.class);
//                                    startActivity(intent);
//                                }
                            }else{

                                if (response.getMessage().equals("")) {
                                    switch (response.getCondition()) {
                                        case "verify":
                                            renderVerify();
                                            break;
                                        case "charge":
                                            renderMoney();
                                            break;
                                        case "personal":
                                            CompleteAccount();
                                            break;
                                        case "demand":
                                            AddDemand();
                                            break;

                                        default:
                                    }
                                }else{
                                    Dialog alertDialog = new AlertDialog.Builder(getContext()).
                                            setTitle("信息").
                                            setMessage(response.getMessage()).
                                            setIcon(R.drawable.ic_launcher).
                                            setPositiveButton("确定", new DialogInterface.OnClickListener() {

                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    switch (response.getCondition()) {
                                                        case "verify":
                                                            renderVerify();
                                                            break;
                                                        case "charge":
                                                            renderMoney();
                                                            break;
                                                        case "personal":
                                                            CompleteAccount();
                                                            break;
                                                        case "demand":
                                                            AddDemand();
                                                            break;

                                                        default:
                                                    }
                                                }
                                            }).
                                            create();
                                    alertDialog.show();
                                }
                            }

                        }else{
                            Toast.makeText(getContext(),"抱歉,处理失败，请重试。",Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    protected void onCancelled() {
                        progressDialog.dismiss();
                    }
                };
        task.execute((Void) null);

    }


    private  void changeProfile( final String att, final String content){
        AsyncTask<Void, Void, Boolean> task = new AsyncTask<Void, Void, Boolean>() {
            @Override
            protected Boolean doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<BaseResponse> responseCall = svc.setProfileAttr(WoyaoooApplication.userId,att,content);
                Boolean ret = true ;
                try {
                    BaseResponse response = responseCall.execute().body();
                    ret= response.isSuccess();
                } catch (IOException e) {
                    e.printStackTrace();
                    ret = false;
                }
                return ret;
            }

            @Override
            protected void onPostExecute(final Boolean success) {
                if (success) {
                    getChances("");
//                    Toast.makeText(getContext(), "需求已经修改", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(getContext(), "发生异常，请重试", Toast.LENGTH_LONG).show();
                }
            }

            @Override
            protected void onCancelled() {
                Toast.makeText(getContext(), "发生异常，请重试", Toast.LENGTH_LONG).show();
            }
        };
        task.execute((Void) null);

    }
  
    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onChancesFragmentInteraction(uri);
        }
    }
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof ChancesFragment.OnChancesFragmentInteractionListener) {
            mListener = (ChancesFragment.OnChancesFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnChancesFragmentInteractionListener {
        // TODO: Update argument type and name
        void onChancesFragmentInteraction(Uri uri);
        void onMessage( Integer messageNum, String info);
    }


    private boolean checkStoragePermission() {
        String[] permissions = new String[]{ Manifest.permission.WRITE_EXTERNAL_STORAGE};
        boolean authorized = true ;
        mPermissionList.clear();

        //判断哪些权限未授予
        for (int i = 0; i < permissions.length; i++) {
            if (ContextCompat.checkSelfPermission(getContext(), permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                mPermissionList.add(permissions[i]);
            }
        }
        /**
         * 判断是否为空
         */
        if (mPermissionList.isEmpty()) {//未授予的权限为空，表示都授予了

        } else {//请求权限方法
            requestPermissions( permissions, PERMISSION_REQUEST_STORAGE);
            authorized = false ;
        }
        return authorized;
    }

    /**
     * 显示下载进度对话框
     */
    public void showDownloadDialog() {

        progressDialog = new ProgressDialog(getContext());
        progressDialog.setTitle("正在下载...");
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setCancelable(false);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

        new ChancesFragment.downloadAsyncTask().execute();
    }

    /**
     * 下载新版本应用
     */
    private class downloadAsyncTask extends AsyncTask<Void, Integer, Integer> {

        @Override
        protected void onPreExecute() {

            progressDialog.show();
        }

        @Override
        protected Integer doInBackground(Void... params) {



            URL url;
            HttpURLConnection connection = null;
            InputStream in = null;
            FileOutputStream out = null;
            try {
                url = new URL(apk_path);
                connection = (HttpURLConnection) url.openConnection();

                in = connection.getInputStream();
                long fileLength = connection.getContentLength();
                File file_path = new File(FILE_PATH);
                if (!file_path.exists()) {
                    file_path.mkdirs();
                }

                out = new FileOutputStream(new File(FILE_NAME));//为指定的文件路径创建文件输出流
                byte[] buffer = new byte[1024 * 1024];
                int len = 0;
                long readLength = 0;


                while ((len = in.read(buffer)) != -1) {

                    out.write(buffer, 0, len);//从buffer的第0位开始读取len长度的字节到输出流
                    readLength += len;

                    int curProgress = (int) (((float) readLength / fileLength) * 100);


                    publishProgress(curProgress);

                    if (readLength >= fileLength) {

                        break;
                    }
                }

                out.flush();
                return 1;

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                if (connection != null) {
                    connection.disconnect();
                }
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {

            progressDialog.setProgress(values[0]);
        }

        @Override
        protected void onPostExecute(Integer integer) {

            progressDialog.dismiss();//关闭进度条
            //安装应用
            installApp();
        }
    }

    /**
     * 安装新版本应用
     */
    private void installApp() {
        File appFile = new File(FILE_NAME);
        if (!appFile.exists()) {
            return;
        }
        // 跳转到新版本应用安装页面
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri apkUri = FileProvider.getUriForFile(getContext(), "com.woyao.app.fileprovider", appFile);//在AndroidManifest中的android:authorities值
            Log.d("======", "apkUri=" + apkUri); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(appFile), "application/vnd.android.package-archive");
        }
        startActivityForResult(intent, INSTALL_CODE);


    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == INSTALL_CODE){

            Log.e("woyaooo", "installed");
            Common.alert(getContext(),"升级完成");
        }


        if  (requestCode == COMPLETE_ACCOUNT_CODE ){
            String displayName = data.getStringExtra("displayname");
            uvm.getUser().setDisplayname( displayName);
            loadProfile();


        }



        if  (requestCode == MODIFY_DEMAND_CODE  ){   //add or change demand
            Integer demand_id = data.getIntExtra("demand_id",0);
            if (demand_id == 0) return;

            uvm.getUser().setDemand_id(demand_id);

            chances = new ArrayList<ChanceSummary>();
            loadProfile();



        }

        if  (requestCode == ADD_DEMAND_CODE  ){   //add or change demand
            Integer demand_id = data.getIntExtra("demand_id",0);
            if (demand_id == 0) return;

            uvm.getUser().setDemand_id(demand_id);
            addDemandBtn.setTextColor(ContextCompat.getColor(getContext(), R.color.colorSubTitleText));
            chances = new ArrayList<ChanceSummary>();
            loadProfile();

            Toast.makeText(getContext(),"已经添加",Toast.LENGTH_LONG);


        }
        
        if  (requestCode == COMPLETE_LOCATION_CODE && resultCode ==666 ){
            String locationNo = data.getStringExtra("no");
            String locationName = data.getStringExtra("name");
            uvm.getUser().setLocation(locationName);
            uvm.getUser().setProvince( Integer.parseInt( locationNo));
            changeProfile("location", locationNo);

        }

        if  (requestCode == COMPLETE_CATEGORY_CODE && resultCode ==666 ){
//            String categoryNo = data.getStringExtra("category");
//            String categoryName = data.getStringExtra("category_name");
//
//            uvm.getUser().setCategory(categoryNo);
//            uvm.getUser().setCategory_name( categoryName);
//            changeProfile("category", categoryNo);


            KeyValueList thelist = (KeyValueList) data.getExtras().get("result");
            String nos = Common.KeyValueToNos(thelist.getContent());
            String names = Common.KeyValueToNames(thelist.getContent());
            uvm.getUser().setCategory(nos);
            uvm.getUser().setCategory_name( names);

            changeProfile("category",nos );



        }


        if  (requestCode == COMPLETE_PREFER_CODE && resultCode == 666 ){
            loadProfile();
        }

        if  (requestCode == MYREGISTER_CODE && resultCode == 666 ){
            loadProfile();
            toolbar.setTitle("我要合作网");
        }

        if  (requestCode == MY_LOGIN_CODE && resultCode == 666 ){
            loadProfile();
            toolbar.setTitle("我要合作网");
        }


       
    }

}
